package com.ziyun.pop.mall.base.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @Author:chenxiaoyi
 * @Date:2018/11/6 17:10
 */
public class SerializeUtil {

    private static Logger _log = LoggerFactory.getLogger(SerializeUtil.class);

    public static byte[] serializeToString(Object obj) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream stream = null;
        try {
            stream = new ObjectOutputStream(baos);
            stream.writeObject(obj);
        } catch (IOException e) {
            _log.error("对象序列化error");
        }finally {
            try {
                baos.close();
                stream.close();
            } catch (IOException e) {
                _log.error("序列化对象流关闭失败");
            }
        }
        return baos.toByteArray();
    }

    public static Object deserializeToObject(byte[] bytes) {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        ObjectInputStream stream = null;
        Object o = null;
        try {
            stream = new ObjectInputStream(bais);
            o = stream.readObject();
        } catch (Exception e) {
            _log.error("对象反序列化失败");
        }finally {
            try {
                bais.close();
                stream.close();
            } catch (IOException e) {
                _log.error("反序列化对象流关闭失败");
            }
        }
        return o;
    }

}
